//
//  HLEDownloadRequest.m
//  HLENetwork_Example
//
//  Created by hle1879 on 2020/10/10.
//  Copyright © 2020 13434436448@163.com. All rights reserved.
//

#import "HLEDownloadRequest.h"
#import <AFNetworking/AFNetworking.h>
#import "HLESessionManager.h"
#import "HLEDownLoadResponse.h"

static NSString *const HLEDownload = @"HLEDownload";

@interface HLEDownloadRequest ()

@property (nonatomic,strong) NSURLSessionDownloadTask *task;

@end

@implementation HLEDownloadRequest

-(instancetype)init{
    self = [super init];
    if (self) {
        
    }
    return self;
}

- (void)sendRequest{
    [self addDelegateForDataTask];
    [self logRequestInfo];
    if (!self.url) {
        self.url = @"";
    }
    NSString *downloadDirectory = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:self.folderName ? self.folderName : HLEDownload];
    NSString *fileName = self.url.lastPathComponent;
    NSString *downloadPath = [downloadDirectory stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL fileExist = [fileManager fileExistsAtPath:downloadPath];
    if (fileExist) {
        [fileManager removeItemAtPath:downloadPath error:nil];
    }
    
    BOOL folderExist = [fileManager fileExistsAtPath:downloadDirectory];
    if (folderExist) {
        [fileManager createDirectoryAtPath:downloadDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:self.url]];
    [self disposeRequestMutableHeaderField:request];
    __weak typeof(self) weakSelf = self;
    self.task = [self.session.sessionManager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.progress ? strongSelf.progress(downloadProgress, downloadProgress.fractionCompleted) : nil;
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        return [NSURL fileURLWithPath:downloadPath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        HLEDownLoadResponse *result = [[HLEDownLoadResponse alloc]initWithResponse:response responseObject:nil filePath:filePath error:error];
        strongSelf.responseCompletion ? strongSelf.responseCompletion(result) : nil;
        [strongSelf removeDelegateForDataTask];
        [strongSelf logResponseInfo:result];
    }];
    
    
}

- (void)sendRequestWithResumeData:(NSData * _Nonnull)resumeData{
    [self addDelegateForDataTask];
    [self logRequestInfoForResumeData:resumeData];
    __weak typeof(self) weakSelf = self;
    self.task = [self.session.sessionManager downloadTaskWithResumeData:resumeData progress:^(NSProgress * _Nonnull downloadProgress) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        strongSelf.progress ? strongSelf.progress(downloadProgress, downloadProgress.fractionCompleted) : nil;
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        NSString *downloadDirectory = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:self.folderName ? self.folderName : HLEDownload];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        BOOL folderExist = [fileManager fileExistsAtPath:downloadDirectory];
        if (folderExist) {
            [fileManager createDirectoryAtPath:downloadDirectory withIntermediateDirectories:YES attributes:nil error:nil];
        }
        NSString *filePath = [downloadDirectory stringByAppendingPathComponent:response.suggestedFilename];
        return [NSURL fileURLWithPath:filePath];
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        HLEDownLoadResponse *result = [[HLEDownLoadResponse alloc]initWithResponse:response responseObject:nil filePath:filePath error:error];
        strongSelf.responseCompletion ? strongSelf.responseCompletion( result) : nil;
        [strongSelf removeDelegateForDataTask];
        [strongSelf logResponseInfo:result];
    }];
}


- (void)cancelByProducingResumeData:(HLENetWorkDownloadCancelByResumeData)resumeDataCompletion{
    if (self.task) {
        [self.task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
            resumeDataCompletion ? resumeDataCompletion(resumeData) : nil;
        }];
    }
}
- (void)suspend{
    if (self.task) {
        [self.task suspend];
    }
}

-(void)resume{
    if (self.task) {
        [self.task resume];
    }
}

- (void)logRequestInfo{
#ifdef DEBUG
    if (self.enableLog) {
        NSMutableDictionary *requestHeader = [NSMutableDictionary dictionaryWithDictionary:self.requestHeader];
        if (self.session.config.requestHeader && self.session.config.requestHeader.count > 0) {
            [requestHeader addEntriesFromDictionary:self.session.config.requestHeader];
        }
        
        NSLog(@"\n==================发送请求==================\n\
              \n===下载地址:%@\n\
              \n===下载文件的目录:%@\n\
              \n===请求头:%@\n\
              \n===========================================",
              self.url,
              self.folderName,
              requestHeader);
    }
#endif
}

- (void)logRequestInfoForResumeData:(NSData * _Nonnull)resumeData{
#ifdef DEBUG
    if (self.enableLog) {
        NSMutableDictionary *requestHeader = [NSMutableDictionary dictionaryWithDictionary:self.requestHeader];
        if (self.session.config.requestHeader && self.session.config.requestHeader.count > 0) {
            [requestHeader addEntriesFromDictionary:self.session.config.requestHeader];
        }
        NSMutableDictionary *resumeDataDic =[NSPropertyListSerialization propertyListWithData:resumeData options:NSPropertyListImmutable format:nil error:nil];
        NSString *url = resumeDataDic[@"NSURLSessionDownloadURL"];
        NSLog(@"\n==================发送请求==================\n\
              \n===下载地址:%@\n\
              \n===断点下载开始位置:%lu\n\
              \n===下载文件的目录:%@\n\
              \n===请求头:%@\n\
              \n===========================================",
              url,
              (unsigned long)[resumeData length],
              self.folderName,
              requestHeader);
    }
#endif
}


- (void)logResponseInfo:(HLEDownLoadResponse*)response{
#ifdef DEBUG
    if (self.enableLog) {
        NSLog(@"\n==================请求结束==================\n\
              \n===下载地址:%@\n\
              \n===%@\n\
              \n===========================================",
              self.url,
              (response.success ?
               [NSString stringWithFormat:@"===下载成功的文件路径:%@",response.filePath] :
               [NSString stringWithFormat:@"===下载失败返回:%@",response.error])
              );
    }
#endif
}
@end
